package com.sky.sd.common.web.convert;

import com.baomidou.mybatisplus.core.enums.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/6/10 17:16
 * <br/>修改日期: 2020/6/10 17:16
 * <br/>修改列表:
 */
public class SkyConverterFactory implements ConverterFactory<String, IEnum> {
    @Override
    public Converter getConverter(Class targetType) {

        return new BaseConverter(targetType);
    }

    class BaseConverter<T extends IEnum> implements Converter<String, T> {

        private Class<T> enumType;
        private Map<String, T> enumMap = new HashMap<>();

        public BaseConverter(Class<T> enumType) {
            this.enumType = enumType;
        }


        @Override
        public T convert(String source) {
            for(IEnum sexType : enumType.getEnumConstants()) {
                if(sexType.getValue().equals(source)) {
                    return (T) sexType;
                }
            }
            return null;
        }
    }
}
